package com.jiyun.jiyunmall.product.exception;

import com.jiyun.jiyunmall.common.utils.Result;
import com.jiyun.jiyunmall.common.utils.ResultCode;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.stereotype.Controller;
import org.springframework.validation.DefaultBindingErrorProcessor;
import org.springframework.validation.DefaultMessageCodesResolver;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.UnexpectedTypeException;
import java.util.HashMap;
import java.util.List;

/**
 * @author 86156
 * 文件名: 全局异常处理器
 * 创建者: Z奇
 * 创建时间:2022-08-10 11:44
 * 描述: 全局异常处理器，校验JSR303异常
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler
    public Result bindingExceptionHandler(MethodArgumentNotValidException e){
        System.out.println(e);
        List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
        int errorCount = e.getBindingResult().getErrorCount();
        HashMap<String, String> map = new HashMap<>();
        if (errorCount>0){
            for (ObjectError allError : allErrors) {
                Object[] arguments = allError.getArguments();
                DefaultMessageSourceResolvable dmr = (DefaultMessageSourceResolvable)arguments[0];
                map.put("name",dmr.getDefaultMessage());
                map.put("msg",allError.getDefaultMessage());
            }
            Result error = new Result();
            error.setCode(ResultCode.BINDING_ERROR.getCode());
            error.setMsg(ResultCode.BINDING_ERROR.getMsg());
            error.setData(map);
            return error;
        }
        Result error = new Result();
        error.setCode(400);
        return error;
    }
}
